package com.jwkj.scollect.mock;

import com.jwkj.scollect.collector.queue.SendQueue;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

import com.jwkj.scollect.collector.queue.MessageData;
import com.jwkj.scollect.collector.queue.Metrics;
import com.jwkj.scollect.conf.SpringUtils;
import com.jwkj.scollect.conf.SystemGloble;
import com.jwkj.scollect.model.TblDevice;
import com.jwkj.scollect.model.TblSensor;
import com.jwkj.scollect.service.DeviceService;

public class MockServer {

	public static void init() throws Exception {
		while (true) {
			Thread.sleep(1000*60);
			try {
				DeviceService deviceService = SpringUtils.getBean(DeviceService.class);
				List<TblDevice> devices = deviceService.getDevicesByIp(SystemGloble.getParam(SystemGloble.MOCK_FLAG));
				if(null != devices && devices.size() > 0) {
					for(TblDevice i : devices) {
						List<TblSensor> sensors = deviceService.getSensorByDid(i.getId());
						MessageData message = MessageData.of();
						message.setDeviceId(i.getId());

						for (TblSensor k : sensors) {
							float values = 0.0f;
							if(k.getRemark().equals("jw.co2")) {
								values = nextFloat(420.0f, 435.0f, 0);
							}else if(k.getRemark().equals("jw.dqwd")) {
								values = nextFloat(20.0f, 23.0f, 1);
							}else if(k.getRemark().equals("jw.dqsd")) {
								values = nextFloat(65.0f, 68.0f, 1);
							}else if(k.getRemark().equals("jw.qy")) {
								values = nextFloat(940.0f, 950.0f, 1);
							}else if(k.getRemark().equals("jw.fs")) {
								values = nextFloat(0.5f, 2.0f, 1);
							}else if(k.getRemark().equals("jw.fx")) {
								values = nextFloat(50.5f, 400.0f, 0);
							}else if(k.getRemark().equals("jw.trwd")) {
								values = nextFloat(20.0f, 23.0f, 1);
							}else if(k.getRemark().equals("jw.ph")) {
								values = nextFloat(6.5f, 7.2f, 2);
							}else if(k.getRemark().equals("jw.gzd")) {
								values = nextFloat(0.1f, 1.5f, 1);
							}else if(k.getRemark().equals("jw.trsd")) {
								values = nextFloat(15.0f, 17.0f, 2);
							}
							
							message.put(Metrics.of(k.getRemark(), values, System.currentTimeMillis()/1000, "mock", k.getId(),i.getDevIp()+i.getPort(), i.getId()));
						}
						SendQueue.addMessageData(message);
						
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
        float max = 22.0f;
        float min = 11.0f;
        System.out.println(nextFloat(min - 1, max + 1, 2));
    }
 
    public static float nextFloat(float min, float max, int ws) throws Exception {
        if (max < min) {
            throw new Exception("min < max");
        }
        if (min == max) {
            return min;
        }
        float temp =  min + ((max - min) * new Random().nextFloat());
        BigDecimal b = new BigDecimal(temp);
        return b.setScale(ws,BigDecimal.ROUND_HALF_DOWN).floatValue(); 
    }

}
